"""
    主控制器 控制帧输出和事件
"""
import sys

import pygame

from PyPixelCore.GroupsManager import GroupsManager
from PyPixelCore.Setting import *
from PyPixelCore.block.Bar import Bar
from PyPixelCore.block.TextBlock import TextBlock
from PyPixelCore.panel.EditTextOld import EditTextOld


class PyPixelController:
    def __init__(self):
        # 固定初始化
        pygame.init()
        self.focus_block = None  # 当前点击的焦点块
        self.hovered_button = None  # 鼠标移入的按钮备份
        self.clicked_button = None  # 当前的焦点
        self.screen = pygame.display.set_mode((window_width, window_height))
        self.fps_clock = pygame.time.Clock()
        self.groups_manager = GroupsManager()
        # 设置窗口标题
        if window_text:
            pygame.display.set_caption(window_text)
        # 加载图标
        if window_icon_url:
            # pass
            icon = pygame.image.load(window_icon_url)
            pygame.display.set_icon(icon)

        # 控制器帧函数列表
        self.controller_frame_func = []

        # pygame事件函数字典
        self._key_event_dict = {}

        # # 控制器计时器函数列表 [[timer, func], [timer, func]]
        # self.controller_timer_func = []

        # ***拓展***
        # fps显示
        self.show_fps_block = TextBlock(point_x=400, text_content="fps: 0")
        if show_fps:
            self.groups_manager.add_block(self.show_fps_block)

    def add_block(self, *blocks):
        self.groups_manager.add_block(*blocks)

    def add_controller_frame_func(self, *funcs):
        for func in funcs:
            self.controller_frame_func.append(func)

    def remove_controller_frame_func(self, *funcs):
        for func in funcs:
            self.controller_frame_func.remove(func)

    def add_key_event(self, key_name, key_down_func, key_up_func=None):
        if key_up_func is not None:
            self._key_event_dict[key_name] = [key_down_func, key_up_func]
        else:
            self._key_event_dict[key_name] = [key_down_func, None]

    def reset_key_event(self, key_name, key_down_func=None, key_up_func=None):
        if key_name not in self._key_event_dict:
            return
        if key_down_func is not None:
            self._key_event_dict[key_name][0] = key_down_func
        if key_up_func is not None:
            self._key_event_dict[key_name][1] = key_up_func

    @staticmethod
    def set_caption_text(text):
        pygame.display.set_caption(text)

    @staticmethod
    def set_caption_image(image_url):
        pygame.display.set_icon(pygame.image.load(image_url))

    def _find_hovered_block_by_point(self, point):
        for block in self.groups_manager.click_able_sprites.sprites():
            if block.collision_rect.collidepoint(point):
                self.hovered_button = block
                self.hovered_button.mouse_hover_enter()
                return

    def run(self):
        # 用于计算帧率的变量
        frame_count = 0
        last_time = pygame.time.get_ticks()

        # 游戏循环
        while True:
            # print(self.groups_manager.print_all_groups())
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

                # 鼠标按下事件
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    # 左键事件
                    if event.button == pygame.BUTTON_LEFT:
                        # 执行按下鼠标事件
                        if self.hovered_button:
                            print(self.hovered_button.collision_rect)
                            self.hovered_button.click_down(event.pos)
                            self.clicked_button = self.hovered_button
                        # 焦点处理  在可以焦点的控件中寻找焦点
                        has_focus = False
                        for sprite in self.groups_manager.focus_able_sprites.sprites():
                            if sprite.rect.collidepoint(event.pos):
                                if self.focus_block and self.focus_block != sprite:
                                    self.focus_block.leave_focus_animation(event.pos)
                                self.focus_block = sprite
                                has_focus = True
                                self.focus_block.focus_animation(event.pos)
                                break
                        if not has_focus:
                            if self.focus_block:
                                self.focus_block.leave_focus_animation(event.pos)
                            self.focus_block = None

                    # 向上滚动事件
                    elif event.button == pygame.BUTTON_WHEELUP:
                        if self.focus_block:
                            self.focus_block.wheel_down_animation()
                            self.clicked_button = None  # 或者改为执行松开操作
                            if self.hovered_button:
                                self.hovered_button.mouse_hover_leave()
                                self.hovered_button = None

                    # 向下滚动事件
                    elif event.button == pygame.BUTTON_WHEELDOWN:
                        if self.focus_block:
                            self.focus_block.wheel_up_animation()
                            self.clicked_button = None  # 或者改为执行松开操作
                            if self.hovered_button:
                                self.hovered_button.mouse_hover_leave()
                                self.hovered_button = None

                # 鼠标抬起事件
                elif event.type == pygame.MOUSEBUTTONUP:
                    # 左键事件
                    if event.button == pygame.BUTTON_LEFT:
                        # 处理抬起事件
                        if self.clicked_button and self.clicked_button == self.hovered_button:
                            self.clicked_button.click_up()
                        else:
                            self.clicked_button = None
                        # 焦点处理
                        if self.clicked_button is not None:
                            if isinstance(self.clicked_button, Bar):
                                self.clicked_button = None

                # 鼠标移动事件
                elif event.type == pygame.MOUSEMOTION:
                    if self.clicked_button is not None:
                        if isinstance(self.clicked_button, Bar):
                            self.clicked_button.click_down(event.pos)

                    # 如果浮动到按钮上方触动浮动事件
                    if self.hovered_button:
                        hover_state = self.hovered_button.collision_rect.collidepoint(event.pos)
                        if hover_state:
                            continue  # 提前结束,避免重复计算,提升性能
                        else:
                            self.hovered_button.mouse_hover_leave()
                            self.hovered_button = None
                    self._find_hovered_block_by_point(event.pos)

                # 通过输入法敲击字符事件
                elif event.type == pygame.TEXTEDITING:
                    if self.focus_block:
                        if isinstance(self.focus_block, EditTextOld):
                            self.focus_block.reload_input_preview(event.text)

                # 通过输入法输入汉字事件
                elif event.type == pygame.TEXTINPUT:
                    if self.focus_block:
                        if isinstance(self.focus_block, EditTextOld):
                            bar = self.focus_block.add_text(event.text)
                            if bar:  # 如果这个bar是初始化的bar,动态地添加进入按钮组
                                self.groups_manager.add_click_able_sprites(self.focus_block.bar)
                            self.focus_block.cursor_shine_show = True
                            self.focus_block.cursor_timer.reset_frame()

                # 键盘事件
                elif event.type == pygame.KEYDOWN:
                    if self.focus_block:
                        self.focus_block.do_key_event(event)
                    elif event.key in self._key_event_dict:
                        if self._key_event_dict[event.key][0]:
                            self._key_event_dict[event.key][0](self)


                elif event.type == pygame.KEYUP:
                    if self.focus_block:
                        self.focus_block.do_key_event(event)
                    elif event.key in self._key_event_dict:
                        if self._key_event_dict[event.key][1]:
                            self._key_event_dict[event.key][1](self)

            # 更新帧率计算
            if show_fps:
                current_time = pygame.time.get_ticks()
                elapsed_time = current_time - last_time
                if elapsed_time >= 1000:  # 每秒更新一次帧率
                    self.show_fps_block.set_text_content(f"fps: {frame_count}")
                    self.show_fps_block.reload_image()
                    frame_count = 0
                    last_time = current_time
                else:
                    frame_count += 1

            # 调用控制器函数
            for func in self.controller_frame_func:
                func(self)

            # 更新所有精灵
            self.groups_manager.all_update()

            # 更新屏幕显示
            self.screen.fill(background_color)
            self.groups_manager.all_draw(self.screen)

            pygame.display.update()
            self.fps_clock.tick(fps_limit)

            # self.groups_manager.print_all_groups()



